<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Config;
use App\Models\Data;
use App\Models\Hospital;
use App\Models\Member;
use App\Models\MemberAnswer;
use App\Models\Problem;
use App\Models\QuestionMember;
use App\Models\Vote;
use App\Models\VoteT;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MemberController extends BaseController {

    /**
     *
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $params = $request->all();
        $build = Member::query();
        $pageSize = $request->input('pageSize', 50);

        if (isset($params['name'])){
            $build = $build->where('name', $params['name']);
        }

        if (isset($params['email'])){
            $build = $build->where('email', $params['email']);
        }
        if (isset($params['mobile'])){
            $build = $build->where('mobile', $params['mobile']);
        }

        if (isset($params['password'])){
            $build = $build->where('password', $params['password']);
        }
        $data = $build->paginate($pageSize);
        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return array
     */
    public function import(Request $request)
    {
        //在源生的php代码中是使用$_FILE来查看上传文件的属性
        //但是在laravel里面有更好的封装好的方法，就是下面这个
        //显示的属性更多
        $fileCharater = $request->file('file');
        $success_num = $error_num = 0;
        try {

            if ($fileCharater->isValid()) { //括号里面的是必须加的哦
                //如果括号里面的不加上的话，下面的方法也无法调用的

                //获取文件的扩展名
                $ext = $fileCharater->getClientOriginalExtension();

                if (!in_array($ext, ['xlsx', 'xls'])){
                    throw new AppException('import_type_is_fail');
                }

                //获取文件的绝对路径
                $path = $fileCharater->getRealPath();

                //定义文件名
                $filename = date('Y-m-d-H-i-s').'.'.$ext;

                //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
                Storage::disk('public')->put($filename, file_get_contents($path));

                $directory = storage_path('app') . '/public';

                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
                # 打开文件、载入excel表格
                $spreadsheet = $reader->load($directory . '/' . $filename);
                # 获取活动工作薄
                $sheet = $spreadsheet->getActiveSheet();

                # 获取总列数
                $highestColumn = $sheet->getHighestColumn();
                # 获取总行数
                $highestRow = $sheet->getHighestRow();
                # 列数 改为数字显示
                $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

                for($a = 2;$a <= $highestRow; $a++){
                    $i = 0;
                    $name = $sheet->getCellByColumnAndRow(1,$a)->getValue();
                    $mobile = $sheet->getCellByColumnAndRow(2,$a)->getValue();
                    $email = $sheet->getCellByColumnAndRow(3,$a)->getValue();
                    $row_data = [];
                    for ($column = 1; $column <= $highestColumnIndex; $column++) {
                        $row_data[] = $sheet->getCellByColumnAndRow($column, $a)->getValue();
                        $i++;
                    }
                    if(!implode('',$row_data)){
                        //删除空行
                        continue;
                    }

                    $data = [
                        'name' => $name,
                        'mobile' => $mobile,
                        'email' => $email,
                    ];
                    //根据传入信息判断角色

                    $result = Member::query()->create($data);
                    if ($result){
                        $success_num = $success_num +1;
                    }else{
                        $error_num = $error_num + 1;
                    }
                }
            }
            $data['success_num'] = $success_num;
            $data['error_num'] = $error_num;
            return $this->success($data);

        } catch (\ Exception $exception) {
            throw new AppException($exception->getMessage());

        }

    }


    public function destroy($memberId, Request $request)
    {
        $memberData = Member::query()->where('member_id', $memberId)->first();

        if (!$memberData){
            throw new AppException('find_member_is_fail');
        }

        $result = $memberData->delete();
        return $this->success($result, '删除成功');

    }

    public function getMemberRole($data)
    {
        if ($data['team_info'] == ''){
            return Member::team;
        }
        if ($data['rm_info'] == ''){
            return Member::rm;
        }
        if ($data['dm_info'] == ''){
            return Member::dm;
        }
        return Member::mr;
    }

    /**
     * 导出excel
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws AppException
     */
    public function export(Request $request)
    {
        try {
            $directory = storage_path();
            $fileName = rand(1000, 9999) . time() . ".xlsx";//导出文件名
            $header = [
                'name' => '姓名', 'mobile' => '电话', 'email' => '邮箱',
                'province' => '省份', 'department' => '科室', 'hospital' => '医院',
                'score' => '可用积分', 'all_score' => '总积分'
            ];
            $widthArray = ['A' => 10, 'B' => 10, 'C' => 10, 'D' => 10, 'E' => 10];
            $build = Member::query();
            $service = new ExcelExportService();
            $service->exportDataBySheet($directory, $fileName, $build, $header, '', 2000, $widthArray);
            return response()->download($directory . '/' . $fileName, '导出文件.xlsx', $headers = ['Content-Type' => 'application/zip;charset=utf-8']);
        } catch (\ Exception $exception) {
            echo $exception->getMessage();die;
            throw new AppException('export_fail');
        }
    }

    public function login(Request $request)
    {
        $params = $request->all();
        $memberMobile = Member::query()
            ->where('mobile', $params['mobile'])
            ->first();
        if (!$memberMobile){
            return $this->errorCode('100002', [], '此手机号未注册');
        }

        if (!isset($params['name']) || !isset($params['mobile'])){
            return $this->errorCode('100001', [], '参数不正确');
        }

        $member = Member::query()
            ->where('name', $params['name'])
            ->where('mobile', $params['mobile'])
            ->first();
        if (!$member){
            return $this->errorCode('10001', [], '账号信息输入错误');
        };

        $member = $member->toArray();

        if ($member['status'] == 0){
            return $this->errorCode('10002', [], '账号未经审核,禁止登录');
        }
        //查看 自己是第几名
        $resultAll = Member::query()->where('all_score', '>', $member['all_score'])->get()->toArray();

        $member['rank'] = count($resultAll) + 1;
        //登录用户投票内容

        return $this->success($member);
    }

    public function update($id, Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        $data = Member::query()->where('member_id', $id)->first();
        if (!$data){
            throw new AppException('find_member_is_fail');
        }

        unset($params['member_id']);
        $updateParams  = [];
        $updateParams['province'] = $params['province'];
        $updateParams['mobile'] = $params['mobile'];
        $updateParams['name'] = $params['name'];
        $updateParams['hospital'] = $params['hospital'];
        $updateParams['department'] = $params['department'];
        $result = Member::query()->where('member_id', $id)->update($updateParams);
        return $this->success($result, '修改成功');
    }

    public function auditMember($id, Request $request)
    {
        $params = $request->all();
        $data = Member::query()->where('member_id', $id)->first();
        if (!$data){
            throw new AppException('find_member_is_fail');
        }
        if (!isset($params['status'])){
            return $this->errorCode('10001', [], '参数错误');
        }

        $result = Member::query()->where('member_id', $id)->update(['status' => $params['status']]);
        return $this->success($result, '操作成功');
    }

    public function hospitalAdd(Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        $data = Member::query()->where('name', $params['name'])->first();
        if ($data){
            return $this->error([], '用户已经存在');
        }
        $result = Member::query()->create($params);
        return $this->success($result, '注册成功');

    }

    public function MemberInfo($id, Request $request)
    {
        $result = Member::query()->where('member_id', $id)->first()->toArray();
        $memberAnswer = MemberAnswer::query()->where('uid', $id)->get()->toArray();
        $memberAnswerRight = MemberAnswer::query()->where('uid', $id)->where('is_correct', Problem::PROBLEM_RIGHT)->get()->toArray();
        $result['all_problem'] = count($memberAnswer);

        if (count($memberAnswerRight) > 0){
            $result['right_rate'] =  $this->formatDecimal(round(count($memberAnswerRight)/count($memberAnswer), 4), 2);

        }else{
            $result['right_rate'] =  0;

        }


        return $this->success($result, '获取成功');
    }

    public function rank($id, Request $request)
    {
        $params = $request->all();
        $num = $params['num'];
        $result = Member::query()->where('all_score', '>', 0)->orderBy('all_score', 'desc')->limit($num)->get()->toArray();

        //查看 自己是第几名
        $member = Member::query()->where('member_id', $id)->first()->toArray();
        $resultAll = Member::query()->where('all_score', '>', $member['all_score'])->get()->toArray();
        $rank = count($resultAll) + 1;
        if ($member['all_score'] == 0){
            $rank = 0;
        }
        return $this->success(['data' =>$result, 'rank' => $rank], '获取成功');
    }

    public function indexConfig(Request $request)
    {
        $config = Config::query()->where('id' , 1)->first();
        return $this->success($config, '获取成功');

    }

    public function updateConfig($id, Request $request)
    {
        $params = $request->all();
        $status = $params['status'];
        $result = Config::query()->where('id', 1)->update(['status'=> $status]);
        return $this->success($result, '更新成功');

    }

    public function receive($id, Request $request)
    {
        $params = $request->all();
        if (!isset($params['type'])){
            return $this->errorCode('10001', [], '参数错误领取失败');
        }
        $type = $params['type'];
        if ($type == 1){
            //1500奖品
            $result = Member::query()->where('member_id', $id)->update(['one_status'=> Member::STATUS_TWO]);


        }elseif ($type == 2){
            $result = Member::query()->where('member_id', $id)->update(['two_status'=> Member::STATUS_TWO]);

            //4500奖品
        }else{
            //100道题领取
            $result = Member::query()->where('member_id', $id)->update(['hundred_reward'=> 1]);

        }
        return $this->success($result, '更新成功');
    }


    public function achievementList(Request $request)
    {
        $params = $request->all();
        if (!isset($params['type'])){
            return $this->errorCode('10001', [], '参数错误');
        }

        $result = [];
        if ($params['type'] == 1){
            //答题满100的 客户列表
            $result = Member::query()->where('num', '>=', 20)->get();

        }elseif ($params['type'] == 2){
            //达到1500分
            $result = Member::query()->where('all_score', '>=', 1500)->get();

        }elseif ($params['type'] ==3){
            //达到4500分
            $result = Member::query()->where('all_score', '>=', 4500)->get();
        }else{

        }
        return $this->success($result, '获取成功');
    }

    public function achievementListExport(Request $request)
    {
        $params = $request->all();
        try {
            $directory = storage_path();
            $fileName = rand(1000, 9999) . time() . ".xlsx";//导出文件名
            $header = [
                'name' => '姓名', 'mobile' => '电话', 'email' => '邮箱',
                'province' => '省份', 'department' => '科室', 'hospital' => '医院',
                'score' => '可用积分', 'all_score' => '总积分'
            ];
            $widthArray = ['A' => 10, 'B' => 10, 'C' => 10, 'D' => 10, 'E' => 10];
            $build = Member::query();
            if ($params['type'] == 1){
                //答题满100的 客户列表
                $build->where('num', '>=', 20);

            }elseif ($params['type'] == 2){
                //达到1500分
                $build->where('all_score', '>=', 1500);

            }elseif ($params['type'] ==3){
                //达到4500分
                $build->where('all_score', '>=', 4500);
            }else{

            }
            $service = new ExcelExportService();
            $service->exportDataBySheet($directory, $fileName, $build, $header, '', 2000, $widthArray);
            return response()->download($directory . '/' . $fileName, '导出文件.xlsx', $headers = ['Content-Type' => 'application/zip;charset=utf-8']);
        } catch (\ Exception $exception) {
            echo $exception->getMessage();die;
            throw new AppException('export_fail');
        }
    }


    /**
     * 处理小数点
     * @param $data
     * @param $number
     * @return false|string
     */
    function formatDecimal($data, $number)
    {
        $data = $data * 100;
        $pos = stripos((string)$data, '.');
        return substr((string)$data, 0, $pos + $number + 1);
    }

    /**
     * 投票给医院
     * @param $id
     * @param Request $request
     * @return array
     * @throws AppException
     */
    public function voteT($id, Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        $data = Hospital::query()->where('hid', $id)->first();
        if (!$data){
            throw new AppException('find_hospital_is_fail');
        }

        if (!isset($params['open_id'])){
            return $this->errorCode('10001', [], 'open_id错误');
        }

        $openId = $params['open_id'];

        //插入投票明细表
        $data = $data->toArray();
        $vote = VoteT::query()->where('open_id', $openId)->get();
        if (count($vote) >= 2){
            return $this->errorCode('10001', [], '您的投票次数已经用完');
        }
        $vote = VoteT::query()->where('open_id', $openId)->where('hospital_id', $id)->first();
        if ($vote){
            return $this->errorCode('10001', [], '您已经投过此医院');
        }

        VoteT::query()->create([
            'open_id' => $params['open_id'],
            'hospital_id' => $id
        ]);


        return $this->success($vote, '投票成功');

    }

    public function getHos()
    {
        $hos = Hospital::query()->where('status', 1)->get()->toArray();

        $voteT = VoteT::query()->count();

        foreach ($hos as $key => $value)
        {
            $thisH = VoteT::query()->where('hospital_id', $value['hid'])->get();
            $hos[$key]['num'] = count($thisH);
            $hos[$key]['allNum'] = $voteT;
        }

        return $this->success($hos, '获取成功');
    }



}
